package com.common.myspring.core.proxy;

import com.common.myspring.core.ApplicationContext;
import com.common.myspring.function.AdviceInterface;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @title: JdkProxy
 * @Author xu-xiang
 * @Date: 2023/8/30 16:57
 * @description:
 */
public class CglibProxy<T> implements MethodInterceptor {

    private final T bean;

    public CglibProxy(T bean) {
        this.bean = bean;
    }

    @SuppressWarnings("unchecked")
    public T doProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(bean.getClass());
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    public static <T> T createProxyObject(T bean) {
        return new CglibProxy<>(bean).doProxy();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        List<AdviceInterface> adviceList = ApplicationContext.getAdvice(bean.getClass(), method);

        if (adviceList == null || adviceList.isEmpty()) {
            return method.invoke(bean, objects);
        }

        // todo 目前只允许增强一次, list = 1
        System.err.println("Cglib代理方法" + method.getName() + "执行开始!");
        for (AdviceInterface advice : adviceList) {
            return advice.around(bean, method, objects);
        }

        return null;
    }
}
